<template>
    <view>
        <view class="head_box bg-white">
            <view>
                <van-search shape="round" :value="search" placeholder="输入商品名称" @change="inputsearch" cancel-class="cancel-class" use-action-slot @clear="onClear">
                    <view slot="action" @tap="gosearch">搜索</view>
                </van-search>
            </view>
            <view class="searchbox padding-lr" v-if="truth">
                <view class="flexbox-sb mrl-20">
                    <text>历史记录</text>
                    <image @tap="onDelete" class="icon-40" :src="imgUrl + 'delete.png'"></image>
                </view>
                <view class="hisbox">
                    <view class="hisitem" :data-value="item" v-if="item" @tap="getData" v-for="(item, index) in historyList" :key="index">{{ item }}</view>
                </view>
            </view>
            <view v-if="!truth" class="padding-tb-xs padding-lr-xl flexs justify-between">
                <view :class="'flexs align-center text-lg ' + (typeActive == 1 ? 'text-orange' : ' text-darkGray')" @tap.stop.prevent="switchType" data-id="1">综合</view>
                <view :class="'flexs align-center text-lg ' + (typeActive == 2 ? 'text-orange' : ' text-darkGray')" @tap.stop.prevent="switchType" data-id="2">销量</view>
                <view :class="'flexs align-center text-lg ' + (typeActive == 3 ? 'text-orange' : ' text-darkGray')" @tap.stop.prevent="switchType" data-id="3">
                    筛选
                    <image src="/static/images/screen.png" class="shangxia margin-left-xs"></image>
                </view>
            </view>
        </view>
        <view style="height: 196rpx"></view>
        <view v-if="!truth && search" class="flexs justify-between padding-lr-sm padding-bottom">
            <view>
                <view
                    class="goods_info radius margin-top-sm bg-white"
                    v-if="index % 2 == 0"
                    @tap="gotoNext"
                    :data-goodsid="item.id"
                    :data-productSn="item.productSn"
                    :data-url="item.url"
                    :data-type="item.type"
                    v-for="(item, index) in goodslist"
                    :key="index"
                >
                    <view class="p-r">
                        <image class="goods_img" mode="widthFix" :src="item.pic" />
                        <view class="goods_sold padding-lr-sm text-sm text-white" v-if="item.sale">已售: {{ item.sale }}</view>
                    </view>

                    <view class="padding-lr-sm margin-tb-sm text-df text-tline">{{ item.name }}</view>

                    <view class="flexs align-center padding-lr-sm padding-bottom-xs flex-wrap">
                        <view v-if="item.price && item.price > 0" class="text-price text-red text-df text-bold padding-right-sm">{{ item.price }}</view>
                        <view class="text-red text-df text-bold padding-right-sm">
                            <block v-if="item.integration && item.price && item.price > 0" class="text-red">+</block>
                            <text v-if="item.integration">{{ item.integration }}意豆</text>
                        </view>
                        <view class="padding-left-sm text-price text-darkGray text-sm text-through" v-if="item.originalPrice && !item.priceMaker && !item.integration">
                            {{ item.originalPrice }}
                        </view>
                        <view class="markerpic" v-if="item.priceMaker">
                            <text class="text-orange">创客</text>
                            <text style="color: #ff1717">￥{{ item.priceMaker }}</text>
                        </view>
                    </view>

                    <view class="padding-lr-sm padding-bottom-sm text-sm text-orange" v-if="item.distributionType != 1 && item.distributionType">支持到店自提</view>
                </view>
            </view>
            <view>
                <view
                    class="goods_info radius margin-top-sm bg-white"
                    v-if="index % 2 == 1"
                    @tap="gotoNext"
                    :data-productSn="item.productSn"
                    :data-goodsid="item.id"
                    :data-url="item.url"
                    :data-type="item.type"
                    v-for="(item, index) in goodslist"
                    :key="index"
                >
                    <view class="p-r">
                        <image class="goods_img" mode="widthFix" :src="item.pic" />
                        <view class="goods_sold padding-lr-sm text-sm text-white" v-if="item.sale">已售: {{ item.sale }}</view>
                    </view>

                    <view class="padding-lr-sm margin-tb-sm text-df text-tline">{{ item.name }}</view>

                    <view class="flexs align-center padding-lr-sm padding-bottom-xs flex-wrap">
                        <view v-if="item.price && item.price > 0" class="text-price text-red text-df text-bold padding-right-sm">{{ item.price }}</view>
                        <view class="text-red text-df text-bold padding-right-sm">
                            <block v-if="item.integration && item.price && item.price > 0" class="text-red">+</block>
                            <text v-if="item.integration">{{ item.integration }}意豆</text>
                        </view>
                        <view class="padding-left-sm text-price text-darkGray text-sm text-through" v-if="item.originalPrice && !item.priceMaker && !item.integration">
                            {{ item.originalPrice }}
                        </view>
                        <view class="markerpic" v-if="item.priceMaker">
                            <text class="text-orange">创客</text>
                            <text style="color: #ff1717">￥{{ item.priceMaker }}</text>
                        </view>
                    </view>

                    <view class="padding-lr-sm padding-bottom-sm text-sm text-orange" v-if="item.distributionType != 1 && item.distributionType">支持到店自提</view>
                </view>
            </view>
        </view>
        <view style="height: 50rpx"></view>
        <!-- 筛选弹窗 -->
        <view class="mask" v-if="active4">
            <view class="maskbox">
                <view style="width: 670rpx; margin-top: 20rpx">
                    <view class="text-black text-df">价格排序</view>
                    <view class="screenboxsbtn">
                        <view data-index="1" @tap="opgaodi" :class="'screenboxsbtnbox ' + (active3 == 1 ? 'gaodis' : '')">从高到低</view>
                        <view data-index="2" @tap="opgaodi" :class="'screenboxsbtnbox ' + (active3 == 2 ? 'gaodis' : '')">从低到高</view>
                    </view>
                    <view class="text-black text-df">价格区间（元）</view>
                    <view class="screenboxsbtn">
                        <view
                            :data-index="index"
                            @tap="bindtapscreen"
                            :class="'screenbtns text-df ' + (active2 == index ? 'active2' : '')"
                            v-for="(item, index) in activelist"
                            :key="index"
                        >
                            {{ item.min }}-{{ item.max }}
                        </view>
                    </view>
                    <view class="screenboxsbtn" style="margin-top: 60rpx">
                        <view class="screenboxsbtnboxs" @tap="chongzhifun">重置</view>
                        <view class="screenboxsbtnboxss screenboxsbtnboxs" @tap="closemak">完成</view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
const _request = require('../../utils/request.js');

const app = getApp();
export default {
    data() {
        return {
            mallimgUrl: app.globalData.mallimgUrl,
            imgUrl: app.globalData.imgUrl,
            //全局img路径
            search: '',
            typeActive: 1,
            //1综合 2销量 3筛选唤起弹窗
            activelist: [
                {
                    min: 0,
                    max: 100
                },
                {
                    min: 100,
                    max: 300
                },
                {
                    min: 300,
                    max: 500
                },
                {
                    min: 500,
                    max: 1000
                }
            ],
            active4: false,
            //筛选弹窗
            active3: -1,
            //价格 1从高到低，2从低到高
            active2: -1,
            //价格区间下标
            toolbarList: [1, 2, 3, 4, 5, 6],
            searchHistoryList: [],
            filterFlag: false,
            queryText: '',
            inputActive: 0,
            goodslist: [],
            showHistoryFlag: true,
            showDelFlag: 0,
            typeActive: 1,
            moneyConfigList: ['0-1000', '1000-3000', '3000-5000', '5000-10000'],
            moneyActive: '',
            minMoney: '',
            maxMoney: '',
            page: 0,
            marker: '',
            //创客价超出显示
            truth: true,
            historyList: []
        };
    },
    onShow: function (options) {
        let mallHistory = uni.getStorageSync('mallHistory');
        this.setData({
            historyList: mallHistory
        });
        console.log(this.historyList);
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.setData({
            page: this.page + 1
        });
        this.querygoods(this.search, this.page, false, false);
    },
    methods: {
        // 获取搜索
        inputsearch(e) {
            let keywork = e.detail.replace(/\s+/g, '');
            this.setData({
                search: keywork,
                page: 0
            });
        },

        // 点击清空
        onClear() {
            this.setData({
                goodslist: null,
                truth: true,
                page: 0
            });
        },

        // 条件查询
        switchType(e) {
            this.setData({
                typeActive: e.currentTarget.dataset.id
            });

            if (e.currentTarget.dataset.id == 3) {
                //筛选
                this.setData({
                    active4: true
                });
            } else {
                //排序
                this.setData({
                    active4: false,
                    active3: -1,
                    active2: -1
                });
                this.querygoods(this.search, this.page, false, true);
            }
        },

        // 搜索
        gosearch() {
            let search = this.search;

            if (search) {
                this.setData({
                    typeActive: 1,
                    active4: false,
                    active3: -1,
                    active2: -1,
                    truth: search.length == 0 ? true : false
                });
                this.querygoods(search, this.page, false, true);
            } else {
                uni.showToast({
                    title: '请输入商品名称',
                    icon: 'none'
                });
            }
        },

        // 价格排序
        opgaodi(e) {
            this.setData({
                active3: e.currentTarget.dataset.index
            });
        },

        // 价格区间
        bindtapscreen(e) {
            if (this.active2 == e.currentTarget.dataset.index) {
                this.setData({
                    active2: 1
                });
                return;
            }

            this.setData({
                active2: e.currentTarget.dataset.index
            });
            console.log(this.active2);
        },

        // 重置
        chongzhifun() {
            this.setData({
                active3: -1,
                active2: -1
            });
        },

        // 完成筛选
        closemak() {
            if (this.active3 < 0 && this.active2 < 0) {
                this.setData({
                    typeActive: 1
                });
            }

            this.querygoods(this.search, this.page, false, false);
            this.setData({
                active4: false
            });
        },

        //点击了删除
        onDelete() {
            uni.setStorageSync('mallHistory', []);
            this.setData({
                historyList: []
            });
        },

        // 点击历史记录
        getData(e) {
            const search = e.currentTarget.dataset.value;
            this.setData({
                search: search,
                truth: false
            });
            this.querygoods(search, this.page, false, false);
        },

        // 去重,保留最新输入值
        noRepeat(value, arr) {
            if (!arr) {
                return [value];
            }

            let newArr = arr?.filter((item) => {
                return item != value;
            });
            return [value, ...newArr];
        },

        // 商品列表
        querygoods(search, page, show, bool) {
            this.setData({
                showHistoryFlag: false
            });
            let mallHistory = uni.getStorageSync('mallHistory');

            if (show) {
                uni.showNavigationBarLoading(); // 顶部加载状态
            }

            console.log(mallHistory.includes(search)); // 点击历史记录

            if (bool && search && !mallHistory.includes(search)) {
                let newHistory = [search, ...mallHistory];
                uni.setStorageSync('mallHistory', newHistory);
                this.setData({
                    historyList: newHistory
                });
                console.log('ww'); // 重复值不存值,替换最新
            } else {
                let array = [];
                array = this.noRepeat(search, mallHistory);
                uni.setStorageSync('mallHistory', array);
                this.setData({
                    historyList: array
                });
            }

            _request
                .get(
                    '/mall-product/list',
                    {
                        // status: self.data.active,
                        offset: page,
                        pageSize: 20,
                        type: 1,
                        search: search,
                        priceInterval: this.active2 + 1,
                        userId: uni.getStorageSync('userId'),
                        sort: this.typeActive == 1 ? '' : this.typeActive == 2 ? 1 : this.active3 == 2 ? 3 : this.active3 == 1 ? 2 : ''
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        let list = res.data.data || [];
                        list.forEach((e) => {
                            if (e.priceMaker) {
                                let str = e.priceMaker.toString();

                                if (str.length > 6 || e.productType == 3) {
                                    e.marker = true;
                                } else {
                                    e.marker = false;
                                }
                            } else if (e.price) {
                                let price = e.price.toString();

                                if (price.length > 4 && e.productType == 3) {
                                    e.prices = true;
                                } else {
                                    e.prices = false;
                                }
                            }
                        });

                        if (list.length > 0) {
                            this.setData({
                                truth: false
                            });
                        }

                        this.setData({
                            goodslist: this.page > 0 ? [...this.goodslist, ...list] : list
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none'
                        });
                    }

                    if (show) {
                        uni.hideNavigationBarLoading(); //完成停止加载
                    }

                    uni.stopPullDownRefresh(); //停止下拉刷新
                })
                .catch((error) => {
                    console.log(error, 'error');

                    if (show) {
                        uni.hideNavigationBarLoading(); //完成停止加载
                    }

                    uni.stopPullDownRefresh(); //停止下拉刷新
                });
        },

        // 跳转
        gotoNext: function (e) {
            if (e.currentTarget.dataset.type == 2 || e.currentTarget.dataset.type == 3) {
                uni.navigateTo({
                    url: '/pagesb/detailed/detailed?productsn=' + e.currentTarget.dataset.productsn + '&goodsid=' + e.currentTarget.dataset.goodsid
                });
            } else {
                uni.navigateTo({
                    url: '/shopingmall/goodsdetail/goodsdetail' + this.getparams(e.currentTarget.dataset)
                });
            }
        },

        getparams: function (item) {
            const list = [];

            for (const key in item) {
                if (key === 'url') {
                    continue;
                }

                list.push(key + '=' + item[key]);
            }

            if (list.length) {
                return '?' + list.join('&');
            } else {
                return '';
            }
        }
    }
};
</script>
<style>
page {
    background: #f8f8f8;
}
.head_box {
    width: 750rpx;
    position: fixed;
    left: 0;
    height: 196rpx;
    z-index: 99;
}
.search {
    width: 620rpx;
    height: 70rpx;
    background: #eeeeee;
}
.search_img1 {
    width: 28rpx;
    height: 28rpx;
}
.shangxia {
    width: 32rpx;
    height: 32rpx;
}

.markerpic {
    height: 34rpx;
    background: #fff6ef;
    border: 1rpx solid #ff8722;
    border-radius: 4rpx;
    justify-content: center;
    display: flex;
    align-items: center;
    font-size: 22rpx;
    /* margin-left: 20rpx; */
    padding: 0 10rpx;
}

.searchbox {
    margin: 40rpx 0;
}

.hisbox {
    margin-top: 30rpx;
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;
    max-height: 400rpx;
}

.hisitem {
    height: 52rpx;
    background: #f2f2f2;
    padding: 0 24rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 52rpx;
    width: fit-content;
    margin: 0 20rpx 30rpx 20rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 筛选弹窗 */
.mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    z-index: 50;
}
.maskbox {
    position: fixed;
    top: 196rpx;
    width: 100%;
    height: 500rpx;
    display: flex;
    justify-content: center;
    background: #fff;
}
.screenboxsbtn {
    display: flex;
    justify-content: space-between;
    margin: 40rpx 0;
}
.screenboxsbtnbox {
    width: 300rpx;
    height: 54rpx;
    border: 3rpx solid #e2e2e2;
    line-height: 54rpx;
    text-align: center;
    color: #999999;
    font-size: 28rpx;
}
.screenboxsbtnboxs {
    width: 260rpx;
    height: 82rpx;
    border: 3rpx solid #ff8722;
    text-align: center;
    line-height: 82rpx;
    border-radius: 41rpx;
    color: #ff8722;
    font-size: 32rpx;
}
.screenboxsbtnboxss {
    background: #ff8722;
    color: #fff;
}
.gaodis {
    border-color: #ff8722;
    background: #fedec2;
    color: #ff8722;
}
.screenbtns {
    padding: 0 10rpx;
    line-height: 42rpx;
    height: 42rpx;
    border: 1rpx solid #999999;
    border-radius: 21rpx;
    color: #999999;
}
.active2 {
    border: 1rpx solid #ff8722;
    background: #fedec2;
    color: #ff8722;
}
/* 列表样式 */
.goods_info {
    width: 340rpx;
    position: relative;
    box-shadow: 2px 4px 8px 0px #f5f5f5;
}
.goods_img {
    width: 340rpx;
    height: 340rpx;
}
.goods_sold {
    position: absolute;
    left: 0;
    bottom: 10rpx;
    line-height: 46rpx;
    border-radius: 0 20rpx 20rpx 0;
    background-color: rgb(0, 0, 0, 0.5);
}
</style>
